<template>
  <div>
    <el-dialog top="5vh" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="moderVisible"
      :title="title || (Action === 1 ? '添加资产' : '修改资产')" v-el-drag-dialog width="1000px" @close="cancel()">
      <el-form label-width="120px" :rules="rules" :model="Moder" ref="Moder" class="ruleDialogForm">
        <el-row class="ruleMain">
          <el-divider content-position="left">资产基本信息</el-divider>
          <el-col :span="16">
            <el-form-item label="部门：" prop="DepartmentID">
              <el-cascader v-model="Moder.DepartmentID" ref="cascaderAddr" placeholder="请选择部门" :options="nodeData"
                :props="{ children: 'Children', label: 'Name', value: 'ID', checkStrictly: true, emitPath: false, expandTrigger: 'hover' }"
                clearable @visible-change="elCascaderOnlick" @expand-change="elCascaderOnlick" style="width: 100%;">
              </el-cascader>
            </el-form-item>
            <el-form-item label="资产名称：" prop="DeviceName">
              <el-input placeholder="请输入资产名称" maxlength="32" v-model="Moder.DeviceName"></el-input>
            </el-form-item>
            <el-form-item label="资产编码：" prop="DeviceCode">
              <el-input placeholder="请输入资产编码" maxlength="16" oninput="value=value.replace(/[^0-9A-Za-z-]/g,'')"
                v-model="Moder.DeviceCode"></el-input>
            </el-form-item>
            <el-form-item label="资产类型：" prop="DeviceType">
              <el-select v-model="Moder.DeviceType" placeholder="请选择资产类型" style="width:100%">
                <el-option v-for="(item, index) in DeviceList" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="核心资产：" prop="Level">
              <el-radio v-model="Moder.Level" :label="1">普通</el-radio>
              <el-radio v-model="Moder.Level" :label="2">核心</el-radio>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="">
              <span>选择头像：</span>
              <div id="upload">
                <el-upload action="#" list-type="picture-card" ref="upload" :class="{ hide: hideUpload }" accept='image/*'
                  :on-change="filechange" :http-request="uploadFileChange" :on-preview="handlePreview"
                  :on-remove="handleRemove" :before-remove="beforeRemove" :limit="1"
                  :on-exceed="handleExceed" :file-list="fileList">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img :src="file.url" class="full-image">
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleMain">
          <el-divider content-position="left">资产认证信息</el-divider>
          <el-col :sm="16" :md="16" :lg="16">
            <el-form-item label="认证模式：" prop="RealnameType">
              <el-radio-group v-model="Moder.RealnameType" @change="RealnameTypeChange">
                <el-radio :label="1">安装代理</el-radio>
                <el-radio :label="2">扫描识别</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="识别模式：" prop="RelnameID">
              <el-radio v-model="Moder.RelnameID" :label="1">mac</el-radio>
              <el-radio v-model="Moder.RelnameID" :label="2" :disabled="Moder.RealnameType === 1">ip</el-radio>
              <el-radio v-model="Moder.RelnameID" :label="3" :disabled="Moder.RealnameType === 1">mac + ip</el-radio>
            </el-form-item>
            <el-form-item label="MAC地址：" prop="HardID">
              <el-input placeholder="请输入MAC地址，例:A1-B2-C3-D4-5E-6F" maxlength="17"
                oninput="value=value.replace(/[^0-9A-F-]/g,'')" v-model="Moder.HardID"></el-input>
            </el-form-item>
            <el-form-item label="IP地址：" prop="DeviceIP">
              <el-input placeholder="请输入IP地址，例:192.168.0.1" maxlength="16" oninput="value=value.replace(/[^0-9.]/g,'')"
                v-model="Moder.DeviceIP"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="ruleMain">
          <el-divider content-position="left">资产详情信息</el-divider>
          <el-col :span="16">
            <el-form-item label="投入使用时间:" prop="StartDate">
              <el-date-picker style="width:100%" v-model="Moder.StartDate" type="date" format="yyyy 年 MM 月 dd 日"
                value-format="timestamp" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="使用角色:" prop="Role">
              <el-select v-model="Moder.Role" placeholder="请选择使用角色" style="width:100%">
                <el-option v-for="(item, index) in RoleList" :key="index" :label="item.Role"
                  :value="item.Role"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="使用者：" prop="UseName">
              <el-input placeholder="请输入使用者" maxlength="32" v-model.trim="Moder.UseName"></el-input>
            </el-form-item>
            <el-form-item label="日志记录级别：" prop="LogLevel">
              <el-radio v-model="Moder.LogLevel" :label="0">不记录</el-radio>
              <el-radio v-model="Moder.LogLevel" :label="1">错误</el-radio>
              <el-radio v-model="Moder.LogLevel" :label="2">错误、告警</el-radio>
              <el-radio v-model="Moder.LogLevel" :label="3">信息、告警、错误</el-radio>
            </el-form-item>
            <el-form-item label="联系电话：" prop="Phone">
              <el-input placeholder="请输入联系电话" oninput="value=value.replace(/[^0-9-]/g,'')" maxlength="11"
                v-model="Moder.Phone"></el-input>
            </el-form-item>
            <el-form-item label="操作系统：" prop="OsInfo">
              <el-select v-model="Moder.OsInfo" placeholder="请选择操作系统" style="width:100%">
                <el-option label="windows" value="windows"></el-option>
                <el-option label="linux" value="linux"></el-option>
                <el-option label="osx" value="osx"></el-option>
                <el-option label="ios" value="ios"></el-option>
                <el-option label="android" value="android"></el-option>
                <el-option label="freebsd" value="freebsd"></el-option>
                <el-option label="vmware" value="vmware"></el-option>
                <el-option label="cisco" value="cisco"></el-option>
                <el-option label="mikrotik" value="mikrotik"></el-option>
                <el-option label="vxworks" value="vxworks"></el-option>
                <el-option label="f5 networks" value="f5 networks"></el-option>
                <el-option label="unix" value="unix"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="系统详情：" prop="OsDetail">
              <el-input placeholder="请输入系统详情" maxlength="64" v-model.trim="Moder.OsDetail"></el-input>
            </el-form-item>
            <el-form-item label="计算机名称：" prop="ComputerName">
              <el-input placeholder="请输入计算机名称" maxlength="64" v-model.trim="Moder.ComputerName"></el-input>
            </el-form-item>
            <el-form-item label="生产厂商：" prop="Factory">
              <el-input placeholder="请输入生产厂商" maxlength="64" v-model.trim="Moder.Factory"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-divider></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="cancel()">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from "@/directive/el-drag-dialog";
import { connrequest, uploadfile } from '@/api/firstPage'
import { macRegex, ipv6Regex, ipv4Regex } from '@/utils/RegularExpression'
import { toTree } from '@/utils/index'
export default {
  directives: { elDragDialog },
  props: {
    Moder: {
      type: Object,
      default: {}
    },
    Action: {
      type: Number,
      default: 1
    },
    moderVisible: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ''
    }
  },
  watch: {
    moderVisible(val) {
      if (val === true) {
        this.GetParamDictRole()
        this.GetDepartment()
        this.GetDeviceType()
        this.FileSize = 0
        if (!this.Moder.FileUUID) {
          this.hideUpload = false
          this.fileList = []
        } else {
          this.fileList = [{ name: this.Moder.FileUUID, url: `/ProfilePhoto/${this.Moder.FileUUID}` }]
          this.hideUpload = true
        }
        this.$nextTick(() => {
          this.$refs.Moder.clearValidate();
        })
      } else {
        this.FileSize = 0
        this.fileList = []
        this.hideUpload = false
      }

    }
  },
  data() {
    return {
      nodeData: [],
      RoleList: [],
      DepartmentList: [],
      DeviceList: [],
      fileList: [],
      Attach: [],
      hideUpload: false,
      rules: {
        DepartmentID: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        DeviceName: [
          { required: true, message: '请输入资产名称', trigger: 'blur' }
        ],
        DeviceType: [
          { required: true, message: '请选择资产类型', trigger: 'change' }
        ],
        Level: [
          { required: true, message: '请选择核心资产', trigger: 'change' }
        ],
        Role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ],
        RealnameType: [
          { required: true, message: '请选择认证模式', trigger: 'change' }
        ],
        RelnameID: [
          { required: true, message: '请选择识别模式', trigger: 'change' }
        ],
        StartDate: [
          { required: true, message: '请选择开始使用日期', trigger: 'change' }
        ],
        UseName: [
          { required: true, message: '请输入使用者', trigger: 'blur' }
        ],
      },
    }
  },
  methods: {
    RealnameTypeChange(row) {
      if (row === 1) {
        this.$set(this.Moder, 'RelnameID', 1)
      }
    },
    async GetParamDictRole() {
      const res = await connrequest('GetParamDictRole')
      this.RoleList = res.Data
    },
    async GetDepartment() {
      const res = await connrequest('GetDepartmentDeviceSumTree')
      res.Data.Name = res.Data.RootName
      this.nodeData = toTree(res.Data.Department, res.Data.RootName)[0]['Children']
    },
    async GetDeviceType() {
      const res = await connrequest('GetDictDeviceType')
      this.DeviceList = res.Data
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' // 检查文件类型是否是JPG或PNG
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    cancel() {
      this.$emit('cancel')
    },
    async submit() {
      this.$refs['Moder'].validate(async (valid) => {
        if (valid) {
          if ((this.Moder.RelnameID === 1 || this.Moder.RelnameID === 3) && !this.Moder.HardID) {
            this.$message.error('请输入Mac地址')
            return false
          }
          if (this.Moder.HardID && !macRegex.test(this.Moder.HardID)) {
            this.$message.error('请输入正确的Mac地址')
            return false
          }
          if ((this.Moder.RelnameID === 2 || this.Moder.RelnameID === 3) && !this.Moder.DeviceIP) {
            this.$message.error('请输入IP地址')
            return false
          }
          if (this.Moder.DeviceIP && !ipv6Regex.test(this.Moder.DeviceIP) && !ipv4Regex.test(this.Moder.DeviceIP)) {
            this.$message.error('请输入正确的IP地址')
            return false
          }
          this.$emit('submit', { ...this.Moder, FileUUID: this.FileUUID }, this.Action)
        }
      })
    },
    elCascaderOnlick() {
      let that = this;
      setTimeout(function () {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function () {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    },
    //级联选项卡点击关闭下拉
    groupOnlick() {
      let that = this;
      setTimeout(function () {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function () {
            this.previousElementSibling.click();
            that.$refs.group.dropDownVisible = false;
          };
        });
      }, 100);
    },
    filechange(file, fileList) {
      let arr = []
      fileList.map(item => {
        arr.push({ OrigFileName: item.name })
      })
      this.Attach = arr
    },
    async uploadFileChange(file) {
      let formData = new FormData();
      formData.append('CmdCode', "UploadFileToTmp");
      formData.append('file', file.file);
      const res = await uploadfile(formData)
      if (res.Status.StatusCode === 0) {
        this.FileSize = file.file.size
        this.$message.success('头像上传成功')
        this.imageUrl = URL.createObjectURL(file.file);
        this.hideUpload = true
        this.FileUUID = res.Data.UUID
      }
    },
    handlePreview() { },
    async handleRemove(file, fileList) {
      const data = {
        Data: {
          FileUUID: file.uid
        }
      }
      const res = await connrequest('DeleteSoftwareDictAttach', data)
      if (res.Status.StatusCode === 0) {
        this.Attach = this.Attach.filter(item => item.uid !== file.uid);
        this.FileSize = 0
        this.fileList = []
        this.hideUpload = false
        this.$message.success('头像删除成功')
      }
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  position: relative;
  height: calc(100vh - 80px);
  /* 设置对话框的高度 */
  overflow-y: auto;
}

/* 设置.el-dialog内部滚动条的宽度和颜色 */
::v-deep .el-dialog .el-dialog__body::-webkit-scrollbar-thumb {
  background-color: #888;
  /* 设置滚动条颜色 */
}

::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
}

/* 自定义样式，让图片铺满 */
.full-image {
  width: 148px;
  height: 148px;
  /* 确保高度也占满 */
  object-fit: cover;
  /* 裁剪图片以填满容器，保持比例 */
  border-radius: 4px;
  /* 保持与 picture-card 一致的圆角 */
}

#upload {
  .hide ::v-deep .el-upload--picture-card {
    display: none;
  }
}</style>